import React, { Component } from 'react'

export class Ball extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bg: props.bg || 'red',
      top: 0,
      left: 0,
      width: 100,
      height: 100,
      xSpeed: props.xSpeed,
      ySpeed: props.ySpeed,
    }
    const duration = 16;
    setInterval(() => {
      const newLeft = this.state.left + this.state.xSpeed * duration / 1000;
      const newTop = this.state.top + this.state.ySpeed * duration / 1000;
      if (newLeft >= window.innerWidth - this.state.width || newLeft <= 0) {
        this.setState({
          xSpeed: -this.state.xSpeed,
        })
      }
      if (newTop >= window.innerHeight - this.state.height || newTop <= 0) {
        this.setState({
          ySpeed: -this.state.ySpeed,
        })
      }
      this.setState({
        top: newTop,
        left: newLeft,
      })
    }, duration);
  }

  render() {
    return (
      <div style={{
        position: 'fixed',
        borderRadius: '50%',
        top: this.state.top,
        left: this.state.left,
        width: this.state.width,
        height: this.state.height,
        backgroundColor: this.state.bg,
      }}></div>
    )
  }
}

export default Ball